package com.supply.dl.app.http;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;


import com.supply.dl.app.AppConfig;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.NetWorkUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Description: 普通事件流转的 观察者不进行数据解析，有别于<linked {@link BaseObserver}
 * Author：skyTian
 * Time:2017/11/3 09:47
 * CopyRight:com,sky
 */
public abstract class NormalObserver<T> implements Observer<T> {

    private LoadingDialog loadingDialog;

    private Context context;

    public NormalObserver() {
    }

    public NormalObserver(Context context) {
        this.context = context;
        if (context != null && context instanceof Activity)
            this.loadingDialog = LoadingDialog.newInstance(null);
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        if (context != null) {
            //对于网络的检查,在没有网络的时候,调用onFailed方法,并且切断与上游的练习
            if (!NetWorkUtils.isNetworkConnected(context.getApplicationContext())) {
                onFailure(AppConfig.NO_NETWORK);
                d.dispose();
                return;
            }

            if (context instanceof Activity)
                loadingDialog.show(context);
        }
    }

    @Override
    public void onNext(@NonNull T data) {

        if (loadingDialog != null)
            loadingDialog.dismiss();
    }

    @Override
    public void onError(@NonNull Throwable e) {
        if (loadingDialog != null)
            loadingDialog.dismiss();

        if (context != null && !(e instanceof ConnectException) && !(e instanceof SocketTimeoutException))
            Toast.makeText(context.getApplicationContext(), DateUtils.getCurrentTime() + " " + e.getMessage(), Toast.LENGTH_LONG).show();

        Log.e("gtx_ok_error", DateUtils.getCurrentTime() + " " + e.getMessage());

        onFailure(AppConfig.NO_NETWORK);
    }

    @Override
    public void onComplete() {
    }

    /**
     * 失败,这里特定指网络连接失败
     *
     * @param msg
     */
    public void onFailure(String msg) {
    }

}
